package netty.chat.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class SimpleChatClient2 {
    private int port;

    public SimpleChatClient2(int port) {
        this.port = port;
    }

    public void start() {
        EventLoopGroup work = new NioEventLoopGroup();//客户端只有一个工作线程池
        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(work)
                    .channel(NioSocketChannel.class)//与server端不一样，NioSocketChannel客户端被创建时使用
                    .handler(new SimpleChatClientInitializer())
                    .option(ChannelOption.SO_KEEPALIVE, true);//设置这里指定的 Channel 实现的配置参数

            Channel channel = bootstrap.connect("127.0.0.1", port).channel();
            BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
            while (true) {
                channel.writeAndFlush(in.readLine() + "\r\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            work.shutdownGracefully();
        }
    }


    public static void main(String[] args) {
        new SimpleChatClient2(8080).start();
        //可以telnet连接测试一下
    }
}
